package com.studor.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.studor.common.Result;
import com.studor.dto.UserCreateRequest;
import com.studor.dto.UserUpdateRequest;
import com.studor.entity.Account;
import com.studor.entity.Student;
import com.studor.service.AccountService;
import com.studor.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/users")
public class AdminUserController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private StudentService studentService;

    @GetMapping("/list")
    @SaCheckLogin
    @SaCheckRole("admin")
    public Result<List<Map<String, Object>>> getUserList() {
        List<Account> accounts = accountService.list();
        List<Student> students = studentService.list();

        // 创建学生ID到学生信息的映射
        Map<Integer, Student> studentMap = students.stream()
                .collect(Collectors.toMap(Student::getId, student -> student));

        List<Map<String, Object>> userList = accounts.stream().map(account -> {
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("id", account.getId());
            userInfo.put("username", account.getUsername());
            userInfo.put("email", account.getEmail());
            userInfo.put("role", account.getRole());
            userInfo.put("registerTime", account.getRegisterTime());

            // 如果是学生，添加学生信息
            if ("stu".equals(account.getRole())) {
                Student student = studentMap.get(account.getId());
                if (student != null) {
                    userInfo.put("name", student.getName());
                    userInfo.put("gender", student.getGender());
                    userInfo.put("major", student.getMajor());
                    userInfo.put("dormitory", student.getDormitory());
                    userInfo.put("roomNum", student.getRoomNum());
                    userInfo.put("bedNum", student.getBedNum());
                    userInfo.put("tele", student.getTele());
                    userInfo.put("inf", student.getInf());
                }
            }

            return userInfo;
        }).collect(Collectors.toList());

        return Result.success(userList);
    }

    @PostMapping("/create")
    @SaCheckLogin
    @SaCheckRole("admin")
    public Result<Account> createUser(@Valid @RequestBody UserCreateRequest request) {
        Account account = accountService.createUser(request);
        return Result.success(account);
    }

    @PutMapping("/update")
    @SaCheckLogin
    @SaCheckRole("admin")
    public Result<Account> updateUser(@Valid @RequestBody UserUpdateRequest request) {
        Account account = accountService.updateUser(request);
        return Result.success(account);
    }

    @DeleteMapping("/{id}")
    @SaCheckLogin
    @SaCheckRole("admin")
    public Result<Void> deleteUser(@PathVariable Integer id) {
        accountService.deleteUser(id);
        return Result.success("用户删除成功");
    }

    @GetMapping("/{id}")
    @SaCheckLogin
    @SaCheckRole("admin")
    public Result<Map<String, Object>> getUserById(@PathVariable Integer id) {
        Account account = accountService.getById(id);
        if (account == null) {
            return Result.error("用户不存在");
        }

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", account.getId());
        userInfo.put("username", account.getUsername());
        userInfo.put("email", account.getEmail());
        userInfo.put("role", account.getRole());
        userInfo.put("registerTime", account.getRegisterTime());

        // 如果是学生，添加学生信息
        if ("stu".equals(account.getRole())) {
            Student student = studentService.getById(id);
            if (student != null) {
                userInfo.put("name", student.getName());
                userInfo.put("gender", student.getGender());
                userInfo.put("major", student.getMajor());
                userInfo.put("dormitory", student.getDormitory());
                userInfo.put("roomNum", student.getRoomNum());
                userInfo.put("bedNum", student.getBedNum());
                userInfo.put("tele", student.getTele());
                userInfo.put("inf", student.getInf());
            }
        }

        return Result.success(userInfo);
    }
}
